Skip to main content
ICT
Lesson A10 - The String Class
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

J. The toString method page 12 of 17

  1. Wouldn’t it be nice to be able to output objects that you have made using the simple line System.out.print(Object name)? Let’s consider the example of the RegularPolygon class discussed in Lesson A6. It would be nice to be able to print out the statistics of your RegularPolygon objects without having to do a lot of System.out.print statements. Thanks to the toString method, you have the ability to do this.

  2. You can create a toString method in any of your classes in the format of public String toString(). Within the toString() method, you can format your class variables into one String object and return that String. Then, when Java encounters your Object in a String format, it will call the toString() method. Let’s look at an example using a RegularPolygon class.

    public String toString(){
    String a = “Sides: ” + getSides();
    a += “ Length: ” + getLength();
    a += “ Area: ” + getArea();
    return a;
    }

    RegularPolygon square = new RegularPolygon(4, 10);
    System.out.println(square);

    Run Output:

    Sides: 4 Length: 10 Area: 100

  3. You must be careful when using this, because you are fixing the format of the output. Oftentimes, you will still want to format your output depending on the specific problem you are solving, but the toString() method provides a simple and quick way to look at the state of your objects. There are also many times when the toString() method will be very useful. Consider a Student class that contains member variables for first name, middle name, last name, a list of classes being taken, the student’s address and phone number, etc. You could easily make a toString() method that would simply output the students first name, middle initial, and last name for quick reference. Every time you design a class, you should stop and think about whether or not your class would benefit from having a toString() method and how you should format this String.
     
Main Previous Next
Contact
 © ICT 2006, All Rights Reserved.